import express from 'express';
import cors from 'cors';
import { promises as fs } from 'fs';
import path from 'path';
  
const app = express();  
app.use(cors());  
app.use(express.json({ limit: '50mb' }));  
  
// 数据存储目录  
const DATA_DIR = './vtj-data';  
const PROJECTS_DIR = path.join(DATA_DIR, 'projects');  
const FILES_DIR = path.join(DATA_DIR, 'files');  
const HISTORY_DIR = path.join(DATA_DIR, 'history');  
const MATERIALS_DIR = path.join(DATA_DIR, 'materials');  
  
// 确保目录存在  
async function ensureDirectories() {  
  await fs.mkdir(DATA_DIR, { recursive: true });  
  await fs.mkdir(PROJECTS_DIR, { recursive: true });  
  await fs.mkdir(FILES_DIR, { recursive: true });  
  await fs.mkdir(HISTORY_DIR, { recursive: true });  
  await fs.mkdir(MATERIALS_DIR, { recursive: true });  
}  
  
// 工具函数  
const readJsonFile = async (filePath) => {  
  try {  
    const data = await fs.readFile(filePath, 'utf8');  
    return JSON.parse(data);  
  } catch (error) {  
    return null;  
  }  
};  
  
const writeJsonFile = async (filePath, data) => {  
  await fs.writeFile(filePath, JSON.stringify(data, null, 2));  
};  
  
// API端点实现  
  
// 1. 获取项目信息  
app.get('/api/projects/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const projectPath = path.join(PROJECTS_DIR, `${id}.json`);  
    const project = await readJsonFile(projectPath);  
      
    if (!project) {  
      return res.status(404).json({ error: 'Project not found' });  
    }  
      
    res.json(project);  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 2. 保存项目信息  
app.put('/api/projects/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const { project, type } = req.body;  
    const projectPath = path.join(PROJECTS_DIR, `${id}.json`);  
      
    await writeJsonFile(projectPath, project);  
    res.json({ success: true });  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 3. 获取文件内容  
app.get('/api/files/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const filePath = path.join(FILES_DIR, `${id}.json`);  
    const file = await readJsonFile(filePath);  
      
    if (!file) {  
      return res.status(404).json({ error: 'File not found' });  
    }  
      
    res.json(file);  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 4. 保存文件内容  
app.put('/api/files/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const file = req.body;  
    const filePath = path.join(FILES_DIR, `${id}.json`);  
      
    await writeJsonFile(filePath, file);  
    res.json({ success: true });  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 5. 删除文件  
app.delete('/api/files/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const filePath = path.join(FILES_DIR, `${id}.json`);  
      
    await fs.unlink(filePath);  
    res.json({ success: true });  
  } catch (error) {  
    if (error.code === 'ENOENT') {  
      res.status(404).json({ error: 'File not found' });  
    } else {  
      res.status(500).json({ error: error.message });  
    }  
  }  
});  
  
// 6. 获取历史记录  
app.get('/api/history/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const historyPath = path.join(HISTORY_DIR, `${id}.json`);  
    const history = await readJsonFile(historyPath);  
      
    res.json(history || {});  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 7. 保存历史记录  
app.put('/api/history/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const history = req.body;  
    const historyPath = path.join(HISTORY_DIR, `${id}.json`);  
      
    await writeJsonFile(historyPath, history);  
    res.json({ success: true });  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 8. 删除历史记录  
app.delete('/api/history/:id', async (req, res) => {  
  try {  
    const { id } = req.params;  
    const historyPath = path.join(HISTORY_DIR, `${id}.json`);  
      
    await fs.unlink(historyPath);  
    res.json({ success: true });  
  } catch (error) {  
    if (error.code === 'ENOENT') {  
      res.json({ success: true }); // 文件不存在也算成功  
    } else {  
      res.status(500).json({ error: error.message });  
    }  
  }  
});  
  
// 9. 保存物料信息  
app.put('/api/materials/:projectId', async (req, res) => {  
  try {  
    const { projectId } = req.params;  
    const materials = req.body;  
    const materialsPath = path.join(MATERIALS_DIR, `${projectId}.json`);  
      
    await writeJsonFile(materialsPath, materials);  
    res.json({ success: true });  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 10. 获取设计器配置  
app.get('/api/extension', async (req, res) => {  
  try {  
    // 返回默认配置或从配置文件读取  
    const config = {  
      version: '1.0.0',  
      features: ['designer', 'preview', 'publish']  
    };  
    res.json(config);  
  } catch (error) {  
    res.status(500).json({ error: error.message });  
  }  
});  
  
// 启动服务器  
const PORT = process.env.PORT || 3001;  
  
ensureDirectories().then(() => {  
  app.listen(PORT, () => {  
    console.log(`VTJ Backend API Server running on port ${PORT}`);  
    console.log(`Data directory: ${DATA_DIR}`);  
  });  
}).catch(error => {  
  console.error('Failed to start server:', error);  
});
